#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Plugin demo escrito por Diego Hahn - 2010

import gtk

import struct
import array

import pluginmanager

@pluginmanager.register('PLUGIN-REGISTER')
def heaven_register(*args, **kwargs):
	return {'Dept.Heaven Decoder':'HEAVEN'}

@pluginmanager.register('HEAVEN-SCAN')
def heaven_scan(*args, **kwargs):
	fd = kwargs['file']
	progbar = kwargs['progbar']

	fd.seek(0xa0, 0)
	if fd.read(12) == 'YGGDRA UNION':
		offsets =  [0x01b88b0, 0x01b9738, 0x01b8860, 0x01b8888, 0x01b88d8, 0x01b8900, 0x01b8928,
					0x01b8978, 0x01b89a0, 0x01b89c8, 0x01b89f0, 0x01b8a40]
	else:
		return []

	results = []
	for index in range(len(offsets)):
		percent = float(index+1)/float(len(offsets))
		progbar.set_text('Dept. Heaven: ' + str(int(percent * 100)) + "%")
		progbar.set_fraction(percent)

		while gtk.events_pending():
			gtk.main_iteration()

		fd.seek(offsets[index], 0)
		results.append( ((struct.unpack('<L', fd.read(4))[0] - 0x08000000), 'HEAVEN') )

	return results

@pluginmanager.register('HEAVEN-DECODER')
def heaven_decoder(*args, **kwargs):
	headerAddress = kwargs['address']
	fd = kwargs['file']

	fd.seek(headerAddress, 0)

	output = array.array('c')

	currentIter = 0
	totalIter = struct.unpack('<H', fd.read(2))[0]

	headerAddress += 2
	dataAddress = headerAddress + (totalIter << 1)

	while currentIter <= totalIter:
		fd.seek(headerAddress, 0)
		headerAddress += 2

		headerPar = struct.unpack('<H', fd.read(2))[0]
		flag = (((headerPar & 0x8000) << 0x10) & 0xFFFFFFFF) >> 0x10
		# flag = 0000h ou 8000h
		if flag == 0:
			# Lê dados da ROM
			fd.seek(dataAddress, 0)
			wordCount = ((headerPar << 0x11) & 0xFFFFFFFF) >> 0x11

			for x in range(wordCount << 1):
				output.append(fd.read(1))
			dataAddress += (wordCount << 1)

		else:
			# Lê dados da RAM
			wordCount = (((headerPar >> 0x0a) & 0x1f) + 2)
			ramDistance = (headerPar & 0x3ff) << 1

			for x in range(wordCount << 1):
				output.append(output[len(output) - ramDistance])

		currentIter += 1
	return output

#@pluginmanager.register('YGGDRA-ENCODER')
#def yggdra_encoder(*args, **kwargs):
#	pass
